import UIKit

class ProjectModifyViewController: BaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ChangePage {
    
    func change(toPage idx: Int) {
        
        if let vc = page.viewControllers?[0] {
            
            if let currentIndex = ctls.index(of: vc) {
                
                if currentIndex < idx {
                    
                    page.setViewControllers([ctls[idx]], direction: .forward, animated: true, completion: nil)
                    
                } else {
                    page.setViewControllers([ctls[idx]], direction: .reverse, animated: true, completion: nil)
                }
                
            }
        }
    }
    
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx > 0 {
                
                return ctls[idx - 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx < ctls.count - 1 {
                
                return ctls[idx + 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed {
            
            let vc = pageViewController.viewControllers![0]
            
            if let index = ctls.index(of: vc) {
                
                slide.slide(toPosition: index)
                
            }
            
        }
    }
    
    
    var applyid = ""
    
    var applyType = ""
    
    var ctls: Array<UIViewController> = []
    
    let page = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
    
    let slide = SlidePageView.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 55)))
    
    let approvalBtn = UIButton(type: .system)
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        approvalBtn.setTitle("审批意见", for: .normal)
        
        approvalBtn.setTitleColor(UIColor.white, for: .normal)
        
        approvalBtn.backgroundColor = UIColor.mainColor
        
        approvalBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        
        approvalBtn.addTarget(self, action: #selector(approvalAction(_:)), for: .touchUpInside)
//        
        for view in page.view.subviews {
            if view is UIScrollView {
                let scroll = view as! UIScrollView
                scroll.bounces = false
            }
        }
        
        page.delegate = self
        
        page.dataSource = self
        
        slide.delegate = self
        
        slide.backgroundColor = UIColor.white
        
        self.view.addSubview(slide)
        
        page.view.backgroundColor = UIColor.white
        
        self.view.addSubview(page.view)
        
        for view in page.view.subviews {
            if let scroll = view as? UIScrollView {
                
                scroll.delegate = slide
                
            }
        }
        
        self.view.addSubview(approvalBtn)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshBtn), name: NSNotification.Name("RefreshDetail"), object: nil)
        
        self.load(with: "detail")
    }
    
    @objc func refreshBtn()->Void{
        self.popobjc()
    }
    
    @objc func approvalAction(_ : UIButton) -> Void {
        
        let approval = ApprovalSuggestionViewController()
        
        approval.applyId = self.applyid
        
        approval.netPath = "projectManage/mobile/sys/approvalprocess/examineApproval"
        
        approval.businessType = self.applyType
        
         self.navigationController?.present(vc: approval)
        
    }
    
    override func viewWillLayoutSubviews() {
        
        super.viewWillLayoutSubviews()
        
        slide.width = self.view.width
        
        approvalBtn.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.height - 55), size: CGSize(width: self.view.width, height: 55))
        
        page.view.frame = CGRect(origin: CGPoint(x: 0, y: slide.bottom), size: CGSize(width: self.view.width, height: self.view.height - slide.height - approvalBtn.height))
        
    }
    
    
    override var names: Array<String> {
        get{
            return ["detail","refresh"]
        }
    }
    
    override func success(for name: String) -> NetSuccess{
        
        func suc(json: JSON)->Void{
            
            slide.configTitles(["基本信息","审批记录"])

            
            print(json)
            
            var contents: Array<Dictionary<String,String?>> = []
            
//            print(json)
            
            let data = json.contents?["data"]?.contents
            
            let changeNum = data?["changenum"]?.rawString() ?? ""
            
            contents.append(["变更申请号":changeNum])
            
            let projectArchivesBO = data?["endProject"]?.contents ?? ["":JSON()]
            
            let projectName = projectArchivesBO["gsProjName"]?.rawString() ?? ""
            
            contents.append(["项目名称":projectName])
            
            let projectNum = projectArchivesBO["projectNumber"]?.rawString() ?? ""
            
            contents.append(["项目编号":projectNum])
        
            contents.append(["所属综合计划": projectArchivesBO["projectname"]?.rawString() ?? ""])
            
            let projectManager = projectArchivesBO["projManager"]?.rawString() ?? ""
            
            contents.append(["项目经理":projectManager])
            
            let projectType = projectArchivesBO["projTypeName"]?.rawString() ?? ""
            contents.append(["项目类型": projectType])
//            switch projectType {
//            case 1:
//                contents.append(["项目类型":"合同开发"])
//            case 2:
//                contents.append(["项目类型":"自主研发"])
//            case 3:
//                contents.append(["项目类型":"生产销售类"])
//            case 4:
//                contents.append(["项目类型":"工程类"])
//            case 5:
//                contents.append(["项目类型":"运维服务类"])
//            case 6:
//                contents.append(["项目类型":"咨询类"])
//            case 7:
//                contents.append(["项目类型":"融资性租赁"])
//            case 8:
//                contents.append(["项目类型":"经营性租赁"])
//            case 9:
//                contents.append(["项目类型":"综合管理类"])
//            case 10:
//                contents.append(["项目类型":"其他类"])
//            case 11:
//                contents.append(["项目类型":"实施类"])
//            default:
//                contents.append(["项目类型":"其他"])
//            }
            
            let projectLevel = projectArchivesBO["projLevelName"]?.rawString() ?? ""
            contents.append(["项目级别":projectLevel])
            
            let requestDepartment = projectArchivesBO["applyDept"]?.rawString() ?? ""
            
            contents.append(["申请部门":requestDepartment])
            
            let assistDepartment = projectArchivesBO["assistDept"]?.rawString() ?? ""
            
            contents.append(["协同部门":assistDepartment])
            
            let projEstimatedRevenue = projectArchivesBO["projEstimatedRevenue"]?.int ?? 0
            
            contents.append(["项目预算收入(元)":String(projEstimatedRevenue / 100).rmbformat])
            
            let projBudget = projectArchivesBO["projBudget"]?.int ?? 0
            
            contents.append(["项目预算成本(元)":String(projBudget).rmbformat])
            
            let changeTitle = data?["changeTitle"]?.rawString() ?? ""
            
            contents.append(["变更标题":changeTitle])
            
            let changeType = data?["changeType"]?.rawValue as? Int ?? 0
            
            switch changeType {
            case 1:
                contents.append(["变更类型":"项目计划变更"])
            case 2:
                contents.append(["变更类型":"项目预算变更"])
            default:
                contents.append(["变更类型":"其他变更"])
            }
            
            let changeLevel = data?["changeLevel"]?.int ?? 0
            
            switch changeLevel {
            case 1:
                contents.append(["变更严重级别":"严重"])
            case 2:
                contents.append(["变更严重级别":"中度"])
                
            default:
                contents.append(["变更严重级别":"中度"])
            }
            
            let modifyer = data?["changeEmp"]?.rawString() ?? ""
            
            contents.append(["变更申请人":modifyer])
            
            let modifyContent = data?["changeContent"]?.rawString() ?? ""
            
            contents.append(["变更内容描述":modifyContent])
            
            let modifyReason = data?["changeContent"]?.rawString() ?? ""
            
            contents.append(["变更原因分析":modifyReason])
            
            let modifyAffect = data?["changeAffect"]?.rawString() ?? ""
            
            contents.append(["变更影响分析":modifyAffect])
            
            let contentsViewController = TitleContentTableViewController()
            
            contentsViewController.source = contents
            
            self.ctls.append(contentsViewController)
            
            self.page.setViewControllers([self.ctls[0]], direction: .forward, animated: false) { (finished) in
                
            }
            
            let approvalList = ApprovalRecordListViewController()

            if let list = data?["approvalProcessList"]?.array {

                approvalList.source = list

            }
            approvalList.tableView.reloadData()
            ctls.append(approvalList)
        }
        
        func refresh(json: JSON)->Void{
            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
                return
            }
            
            if canoperate == true {
                approvalBtn.isEnabled = true
            } else {
                approvalBtn.isEnabled = false
            }
        }
        
        return name == "detail" ? suc : refresh
        
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        return ["id":self.applyid,"businessType":self.applyType]
    }
    
    override func path(for name: String) -> String{
        return "projectManage/mobile/sys/projectchange/view"
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
}
